package com.ltsznh.android.familybooks;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.ltsznh.android.familybooks.account.AccountCategoryActivity;
import com.ltsznh.android.familybooks.category.CategoryActivity;
import com.ltsznh.android.familybooks.db.dbo;
import com.ltsznh.android.familybooks.record.RecordActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

public class MainActivity extends Activity {

    private DrawerLayout drawerLayout;
    private ListView itemDrawer;

    private ActionBarHelper actionBarHelper;
    private ActionBarDrawerToggle actionBarDrawerToggle;


    public static String dayString ="";
    public static String monthStartString = "";
    public static String monthEndString = "";
    public static SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

    public final static int TITLE_MAIN = 0 ;
    public final static int TITLE_IN = 1 ;
    public final static int TITLE_OUT = 2 ;
    public final static int TITLE_OVER = 3 ;

    public final static int ITEM_ACCOUNT = 0 ;
    public final static int ITEM_CATEGORY = 1 ;
    public final static int ITEM_DAY = 2 ;
    public final static int ITEM_MONTH = 3 ;

    private ArrayList<HashMap<String, Object>> listItem;
    private ListView mainList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainList = (ListView) findViewById(R.id.listView_main_list);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        itemDrawer = (ListView) findViewById(R.id.drawer_item_list);
        String[] itemTitles = getResources().getStringArray(R.array.drawer_item);

        drawerLayout.setDrawerListener(new DemoDrawerListener());
        drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        itemDrawer.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_item,itemTitles));
        itemDrawer.setOnItemClickListener(new DrawerItemClickListener());

        actionBarHelper = createActionBarHelper();
        actionBarHelper.init();

        actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,
                R.drawable.ic_drawer,R.string.drawer_open,R.string.drawer_close);

//        数据库初始化
        dbo.initDatabase(this);

        getRang();

        listItem = new ArrayList<HashMap<String, Object>>();
        initMainItem();
//        Log.d("TTTTTT","create");
    }

    @Override
    protected void onStart() {
        super.onStart();
//        if(drawerLayout.)
//        Log.d("TTTTTT","start");
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        actionBarDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        actionBarDrawerToggle.onConfigurationChanged(newConfig);
    }



    protected  void getRang(){
        Calendar calendar = Calendar.getInstance();
        dayString = format.format(calendar.getTime());

        calendar.set(Calendar.DAY_OF_MONTH,1);
        monthStartString = format.format(calendar.getTime());

        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        monthEndString = format.format(calendar.getTime());
    }

    protected void initMainItem(){
        listItem.clear();
        HashMap<String, Object> itemMap;

        itemMap = new HashMap<String, Object>();
        itemMap.put("id", ITEM_DAY);
        itemMap.put("ItemImage", android.R.drawable.ic_menu_today);//图像资源的ID
        itemMap.put("day", getResources().getString(R.string.text_main_item_day));
        itemMap.put("rang",dayString);
        itemMap.put("in", getMoney(new String[]{"I",dayString,dayString}));
        itemMap.put("out", getMoney(new String[]{"O", dayString, dayString}));
        itemMap.put("arrow",android.R.drawable.ic_menu_send);
        listItem.add(itemMap);

        itemMap = new HashMap<String, Object>();
        itemMap.put("id", ITEM_MONTH);
        itemMap.put("ItemImage", android.R.drawable.ic_menu_month);//图像资源的ID
        itemMap.put("day", getResources().getString(R.string.text_main_item_month));
        itemMap.put("rang",monthStartString + " - " + monthEndString);
        itemMap.put("in", getMoney(new String[]{"I",monthStartString,monthEndString}));
        itemMap.put("out", getMoney(new String[]{"O", monthStartString, monthEndString}));
        itemMap.put("arrow",android.R.drawable.ic_menu_send);
        listItem.add(itemMap);

        //生成适配器的Item和动态数组对应的元素
        SimpleAdapter blottersListItemAdapter = new SimpleAdapter(this,listItem, R.layout.main_item,
                new String[] {"ItemImage","day", "rang","in","out","arrow"},
                new int[] {R.id.imageView_mian_item_item,R.id.textView_main_item_day,
                        R.id.textView_main_item_rang,R.id.textView_main_item_in,
                        R.id.textView_main_item_out,R.id.imageView_main_item_arrow}
        );

        mainList.setAdapter(blottersListItemAdapter);

        mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                goBlotters(listItem.get(i));
            }
        });
    }

    private void goMain() {
        initMainItem();
    }

    private void goIn() {

    }

    private void goOut(String invType) {
        listItem.clear();
        String sqlString = "select distinct a.invCategory as invCategory,ifNull(sum(a.yuan),0) as yuan " +
                "from inv_blotters as a left outer join " +
                "(select distinct invCategory,Min(displayOrder) as displayOrder from inv_category group by  invCategory) as b " +
                "on a.invCategory = b.invCategory " +
                "where invType ='" + invType + "' and invDate >= ? and invDate <= ? group by a.invCategory order by b.displayOrder desc";
        dbo.getReadableDatabase(MainActivity.this);
        Cursor invCategoryCursor = dbo.fbSQLite.rawQuery(sqlString,new String[]{monthStartString,monthEndString});
        if(invCategoryCursor.getCount()>0){
            HashMap<String, Object> itemMap;
            invCategoryCursor.moveToFirst();
            do{
                itemMap = new HashMap<String, Object>();
                itemMap.put("id", ITEM_CATEGORY);
                itemMap.put("ItemImage", android.R.drawable.ic_menu_agenda);//图像资源的ID
                itemMap.put("day", invCategoryCursor.getString(invCategoryCursor.getColumnIndex("invCategory")));
                itemMap.put("rang",monthStartString + " - " + monthEndString);
                if(invType.equalsIgnoreCase("O")){
                    itemMap.put("out", invCategoryCursor.getString(invCategoryCursor.getColumnIndex("yuan")));
                }else {
                    itemMap.put("in", invCategoryCursor.getString(invCategoryCursor.getColumnIndex("yuan")));
                }
//                itemMap.put("in", getMoney(new String[]{"I",monthStartString,monthEndString}));

                itemMap.put("arrow",android.R.drawable.ic_menu_send);
                listItem.add(itemMap);
            }while (invCategoryCursor.moveToNext());
        }

        //生成适配器的Item和动态数组对应的元素
        SimpleAdapter blottersListItemAdapter = new SimpleAdapter(this,listItem, R.layout.main_item,
                new String[] {"ItemImage","day", "rang","in","out","arrow"},
                new int[] {R.id.imageView_mian_item_item,R.id.textView_main_item_day,
                        R.id.textView_main_item_rang,R.id.textView_main_item_in,
                        R.id.textView_main_item_out,R.id.imageView_main_item_arrow}
        );

        mainList.setAdapter(blottersListItemAdapter);

        mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                goBlotters(listItem.get(i));
            }
        });
    }

    private void goOver() {
        listItem.clear();
        String sqlString = "SELECT accountCategory,ifNull(sum(case invType when 'I' then yuan when 'O' then -yuan else 0 end),0) as yuan " +
                "FROM inv_blotters " +
                "group by accountCategory " +
                "order by accountCategory";
        dbo.getReadableDatabase(MainActivity.this);
        Cursor accountCategoryCursor = dbo.fbSQLite.rawQuery(sqlString,null);
        if(accountCategoryCursor.getCount()>0){
            HashMap<String, Object> itemMap;
            accountCategoryCursor.moveToFirst();
            do{
                itemMap = new HashMap<String, Object>();
                itemMap.put("id", ITEM_ACCOUNT);
                itemMap.put("ItemImage", android.R.drawable.btn_star_big_on);//图像资源的ID
                itemMap.put("day", accountCategoryCursor.getString(accountCategoryCursor.getColumnIndex("accountCategory")));
                double yuan = accountCategoryCursor.getDouble(accountCategoryCursor.getColumnIndex("yuan"));
                if(yuan < 0){
                    itemMap.put("out", accountCategoryCursor.getString(accountCategoryCursor.getColumnIndex("yuan")));
                }else {
                    itemMap.put("in", accountCategoryCursor.getString(accountCategoryCursor.getColumnIndex("yuan")));
                }
                itemMap.put("arrow",android.R.drawable.ic_menu_send);
                listItem.add(itemMap);
            }while (accountCategoryCursor.moveToNext());
        }

        //生成适配器的Item和动态数组对应的元素
        SimpleAdapter blottersListItemAdapter = new SimpleAdapter(this,listItem, R.layout.main_item,
                new String[] {"ItemImage","day", "rang","in","out","arrow"},
                new int[] {R.id.imageView_mian_item_item,R.id.textView_main_item_day,
                        R.id.textView_main_item_rang,R.id.textView_main_item_in,
                        R.id.textView_main_item_out,R.id.imageView_main_item_arrow}
        );

        mainList.setAdapter(blottersListItemAdapter);

        mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                goBlotters(listItem.get(i));
            }
        });
    }

    protected String getMoney(String[] selectionArgs){
        dbo.getReadableDatabase(this);
        Cursor cursor = dbo.fbSQLite.rawQuery("select ifNull(sum(yuan),0) as yuan from inv_blotters where invType = ? and invDate >= ? and invDate <= ?",selectionArgs);
        String i = "0";
        if(cursor.getCount()>0){
            cursor.moveToFirst();
            i = (cursor.getString(0));
        }
        cursor.close();
        dbo.closeDatabase();
        return i;
    }

    private void goBlotters(HashMap<String, Object> item) {
        int id =(Integer)item.get("id");
        Intent intent = new Intent();
        switch (id){
            case ITEM_ACCOUNT:
                break;
            case ITEM_DAY:
                intent.setClass(this, BlottersActivity.class);
                intent.putExtra("invDate",dayString);
                startActivity(intent);
                break;
            case ITEM_MONTH:
                intent.setClass(this, MonthBlottersActivity.class);
                intent.putExtra("invDate", dayString);
                startActivity(intent);
                break;
            default:
                break;

        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        switch (item.getItemId()) {
            case R.id.action_add:
                intent.setClass(this,RecordActivity.class);
                break;
            case R.id.action_category:
                intent.setClass(this,CategoryActivity.class);
                break;
            case R.id.action_account:
                intent.setClass(this,AccountCategoryActivity.class);
                break;
            case R.id.action_exit:
                exitApp();
                return true;
            default:
                if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
                    return true;
                }
                Log.d(this.getLocalClassName(),"nothing");
                return super.onOptionsItemSelected(item);
        }
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        return true;
    }

    private void exitApp() {
        Intent intent = new Intent();
        intent.setClass(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //注意本行的FLAG设置
//        startActivity(intent);
        finish();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * This list item click listener implements very simple view switching by changing
     * the primary content text. The drawer is closed when a selection is made.
     */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position){
                case TITLE_MAIN:
                    goMain();
                    break;
                case TITLE_IN:
                    goOut("I");
                    break;
                case TITLE_OUT:
                    goOut("O");
                    break;
                case TITLE_OVER:
                    goOver();
                    break;
                default:
                    return;
            }
            if(view != null){
                actionBarHelper.setTitle(((TextView)view).getText().toString());
            }
            drawerLayout.closeDrawer(itemDrawer);
        }
    }

    /**
     * Create a compatible helper that will manipulate the action bar if available.
     */
    private ActionBarHelper createActionBarHelper() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return new ActionBarHelperICS();
        } else {
            return new ActionBarHelper();
        }
    }

    /**
     * Stub action bar helper; this does nothing.
     */
    private class ActionBarHelper {
        public void init() {}
        public void onDrawerClosed() {}
        public void onDrawerOpened() {}
        public void setTitle(CharSequence title) {}
    }

    /**
     * Action bar helper for use on ICS and newer devices.
     */
    private class ActionBarHelperICS extends ActionBarHelper {
        private final ActionBar actionBar;
        private CharSequence drawerTitle;
        private CharSequence title;

        ActionBarHelperICS() {
            actionBar = getActionBar();
        }

        @Override
        public void init() {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
            title = drawerTitle = getTitle();
        }

        /**
         * When the drawer is closed we restore the action bar state reflecting
         * the specific contents in view.
         */
        @Override
        public void onDrawerClosed() {
            super.onDrawerClosed();
            actionBar.setTitle(title);
        }

        /**
         * When the drawer is open we set the action bar to a generic title.
         * The action bar should only contain data relevant at the top level of
         * the nav hierarchy represented by the drawer, as the rest of your content
         * will be dimmed down and non-interactive.
         */
        @Override
        public void onDrawerOpened() {
            super.onDrawerOpened();
            actionBar.setTitle(drawerTitle);
        }

        @Override
        public void setTitle(CharSequence title) {
            this.title = title;
        }
    }

    private class DemoDrawerListener implements DrawerLayout.DrawerListener {
        @Override
        public void onDrawerOpened(View drawerView) {
            actionBarDrawerToggle.onDrawerOpened(drawerView);
            actionBarHelper.onDrawerOpened();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            actionBarDrawerToggle.onDrawerClosed(drawerView);
            actionBarHelper.onDrawerClosed();
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            actionBarDrawerToggle.onDrawerSlide(drawerView, slideOffset);
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            actionBarDrawerToggle.onDrawerStateChanged(newState);
        }
    }

}
